package cn.gs.serializable.serialize;

// @author gs
import cn.gs.serializable.entity.ArrayEntity;
import cn.gs.serializable.entity.IEntity;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SetSerialize extends CollectionSerialize {

    public SetSerialize() {
        super();
    }

    public SetSerialize(ISerialize ss) {
        super(ss);
    }

    public SetSerialize(Class<?> cc) {
        super(cc);
    }

    @Override
    public <T> T toObj(cn.gs.serializable.serialize.ISerialize ctrl, IEntity from, Class<T> clazz) {
        if (!(from instanceof ArrayEntity) || (clazz != null && !Set.class.isAssignableFrom(clazz))) {
            return null;
        }
        T coll = create(clazz, new HashSet());
        List<IEntity> entities = ((ArrayEntity) from).getEntities();
        if (entities.isEmpty()) {
            //no item should be convert.
            return coll;
        }
        if (coll == null || !(coll instanceof Set)) {
            return null;
        }
        Set c = (Set) coll;
        //convert and add items
        for (int i = 0; i < entities.size(); ++i) {
            Object o = serialize(ctrl).toObj(ctrl, entities.get(i), cc);
            c.add(o);
        }
        return coll;
    }
}
